const Koa = require('koa')
const app = new Koa()
const views = require('@ladjs/koa-views')
const json = require('koa-json')
const body_parser = require('koa-bodyparser')
const index = require('./routes/index')
const users = require('./routes/users')
const {HttpException} = require("./util");


// 解析请求携带的数据
app.use(body_parser({
    enableTypes: ['json', 'form', 'text']
}))
// 让返回的json更具有可读性(加了缩进)
app.use(json())

// 静态文件路径
app.use(require('koa-static')(__dirname + '/public'))
// 页面模板解析
app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// 异常捕获
app.use(async (ctx, next) => {
    try {
        await next()
        if (ctx.status === 404) {
            ctx.body = {msg: "404 Not Found",};
        }
        if (ctx.status === 405) {
            ctx.body = {msg: "405 Method Not Allowed",};
        }
    } catch (e) {
        if (e instanceof HttpException) {
            ctx.status = e.status
            ctx.body = {msg: e.message, code: e.status};
            return;
        }
        ctx.status = 500
        ctx.body = {msg: e.message,};
    }
})

// 添加路由
app.use(index.routes()).use(index.allowedMethods())
app.use(users.routes()).use(users.allowedMethods())


module.exports = app


// sequelize-auto -o "./models" -d cors_db -h 127.0.0.1 -u root -p 3306 -x 123456 -e mysql
